package datadir

import (
	"fmt"
	"gitee.com/iscas-system/cluster/pkg/version"
	"os"
)

var (
	//DefaultDataDir     = "/var/lib/rancher/" + version.Program
	//DefaultHomeDataDir = "${HOME}/.rancher/" + version.Program
	//HomeConfig         = "${HOME}/.kube/" + version.Program + ".yaml"
	//GlobalConfig       = "/etc/rancher/" + version.Program + "/" + version.Program + ".yaml"

	// 注意： cas 云平台仅仅支持root用户运行
	//DefaultHomeDataDir    = "${HOME}/iscas/data/" + version.Program
	//HomeConfig            = "${HOME}/iscas/config/" + version.Program + "/" + version.Program + ".yaml"
	DefaultKubeletRootDir = "/root/iscas/data/" + version.Program + "/kubelet"
	DefaultDataDir        = "/root/iscas/data/" + version.Program
	GlobalConfig          = "/root/iscas/config/" + version.Program + "/" + version.Program + ".yaml"
)

func Resolve(dataDir string) (string, error) {
	return LocalHome(dataDir, false)
}

func ResetDefaultDir(dataDir string) error {

	if os.Getuid() != 0 {
		return fmt.Errorf("cas cloud platform must be run as the root user")
	}
	if dataDir != "" {
		DefaultDataDir = dataDir + "/data/" + version.Program
		DefaultKubeletRootDir = dataDir + "/data/" + version.Program + "/kubelet"
		GlobalConfig = dataDir + "/config/" + version.Program + "/" + version.Program + ".yaml"
		//logrus.Infof("---------get kubelet root dir:%s---------", DefaultKubeletRootDir)
		//logrus.Infof("---------get datadir:%s---------", DefaultDataDir)
		//logrus.Infof("---------get GlobalConfig:%s-------", GlobalConfig)
	}
	return nil
}

func LocalHome(dataDir string, forceLocal bool) (string, error) {
	if dataDir == "" {
		if os.Getuid() == 0 && !forceLocal {
			dataDir = DefaultDataDir
		} else {
			//dataDir = DefaultHomeDataDir
			return "", fmt.Errorf("cas cloud platform must be run as the root user")
		}
	}

	return DefaultDataDir, nil
	//dataDir, err := resolvehome.Resolve(dataDir)
	//if err != nil {
	//	return "", errors.Wrapf(err, "resolving %s", dataDir)
	//}
	//
	//return filepath.Abs(dataDir)
}

// 添加yanzichao自研scheduler启动的配置文件
func AddSchedulerConfigPath(dataDir string) (string, error) {
	yamlContent := fmt.Sprintf(
		`apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
  - schedulerName: default-scheduler
    plugins:
      filter:
        enabled:
          - name: SLFilter
          - name: DevFilter
clientConnection:
  kubeconfig: %s`, GlobalConfig)
	dir := DefaultDataDir + "/config"
	filename := "scheduler-config-without-yunikorn.yaml"

	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return "", err
		}
	}
	filePath := dir + "/" + filename
	//logrus.Infof("---------get filePath:%s-------", filePath)
	_, err := os.Stat(filePath)
	if err == nil {
		return filePath, nil
	}

	file, err := os.Create(filePath)
	if err != nil {

		return "", err
	}
	defer file.Close()

	_, err = file.WriteString(yamlContent)
	if err != nil {
		return "", err
	}
	return filePath, nil
}
